package com.aierjun.idcardorclib;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;

import com.googlecode.tesseract.android.TessBaseAPI;
import com.tianruiworkroomidr.Native;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Ani_aierJun on 2017/9/27.
 */

public class IDCardNativeUtils {
    public static TessBaseAPI baseApi;

    public static TessBaseAPI initOCRFile(Context context) {
        try {
            FileUtils.copyAssetFile(context, "eng.traineddata");
            FileUtils.copyAssetFile(context, "TianruiWorkroomOCR.dat");
        } catch (Exception e) {
            Log.e("IDCardNativeUtils", "initFile error!!!!");
        }
        baseApi = new TessBaseAPI();
        baseApi.init(FileUtils.tessPath, "eng");
        baseApi.setVariable("tessedit_char_whitelist", "0123456789Xx");
        return baseApi;
    }

    public static void openIDCardOCR() {
        Native.openIdrEngine(FileUtils.sdPath);
    }

    public static void closeIDCardOCR() {
        Native.closeIdrEngine();
        baseApi.clear();
    }

    public static void startDecodeingThread(final Context context, final Bitmap bitmap2, final CallBack callBack) {
        Thread decodeingThread = new Thread(new Runnable() {
            public void run() {
                int picw = bitmap2.getWidth();
                int pich = bitmap2.getHeight();
                int[] pix = new int[picw * pich];

                bitmap2.getPixels(pix, 0, picw, 0, 0, picw, pich);
                int rlt = 0;

//                rlt = Native.recognizeImage(pix, picw, pich); // ocr

                rlt = Native.recognizeIdrImage(pix, picw, pich); //
                if (rlt != 1) {
                    callBack.callBack(null);
                } else {
                    String[] mwholeTextLine = Native.getWholeTextLineResult();
                    Map<String, String> data = new HashMap<>();
                    for (int i = 0; i < mwholeTextLine.length; i++) {
                        data.put(i + "", mwholeTextLine[i] + "");
                    }
                    callBack.callBack(data);
                }
            }
        });
        decodeingThread.setName("decodeingThread");
        decodeingThread.start();
    }

    public interface CallBack {
        void callBack(Map<String, String> data);
    }
}
